package com.itheima.auth.handle;

import com.itheima.support.Result;
import com.itheima.utils.JwtTokenUtil;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=UTF-8");
		//登入账户信息
		String username = getLoginName(authentication);
		//生成token
		try {
			Result result = new Result(JwtTokenUtil.createToken(username));
			Map param = new HashMap<>();
			param.put("flag",result.isFlag());
			param.put("data",result.getData());
			param.put("message",result.getMessage());
			response.getWriter().write(new JSONObject(param).toString());
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().write(e.getMessage());
		}
	}

	private String getLoginName(Authentication authentication) {
		String username = null;
		Object principal = authentication.getPrincipal();
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else if (principal instanceof Principal) {
			username = ((Principal) principal).getName();
		} else if (principal instanceof String) {
			username = (String) principal;
		}
		return username;
	}

}
